package com.seezoon.application.tcp.executor;

import com.seezoon.domain.dao.mapper.DeviceInfoMapper;
import com.seezoon.domain.dao.po.DeviceInfoPO;
import com.seezoon.domain.service.DeviceInfoService;
import com.seezoon.infrastructure.tcp.codec.JT808;
import com.seezoon.infrastructure.tcp.common.RpcContext;
import com.seezoon.infrastructure.tcp.handler.MessageHandler;
import com.seezoon.infrastructure.tcp.jt808.JT0102;
import com.seezoon.infrastructure.tcp.jt808.JT8001;
import com.seezoon.infrastructure.tcp.jt808.JT8001.ResultCode;
import com.seezoon.infrastructure.tcp.session.Session;
import com.seezoon.infrastructure.tcp.session.SessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @see JT808#终端鉴权
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class JT0102Exe implements MessageHandler<JT0102, JT8001> {

    private final DeviceInfoService deviceInfoService;
    private final DeviceInfoMapper deviceInfoMapper;

    @Override
    public int requestType() {
        return JT808.终端鉴权;
    }

    @Override
    public int responseType() {
        return JT808.平台通用应答;
    }

    @Override
    public JT8001 execute(JT0102 request, RpcContext rpcContext) {
        String simNumber = rpcContext.getSerialNo();
        String authKey = request.getAuthKey();
        DeviceInfoPO deviceInfoPO = deviceInfoMapper.selectBySimNumber(simNumber);
        JT8001 response = new JT8001();
        response.setResponseMsgSerialNo(rpcContext.getMsgSerialNo());
        response.setMsgId(rpcContext.getMsgId());
        if (deviceInfoPO == null) {
            log.error("device:{} not register,auth failed", simNumber);
            response.setResultCode(ResultCode.FAILURE);
            return response;
        }
        if (!StringUtils.equals(authKey, deviceInfoPO.getAuthKey())) {
            log.error("device:{} auth failed,auth key:{} not match", simNumber, authKey);
            response.setResultCode(ResultCode.FAILURE);
            return response;
        }
        // 鉴权通过设置session为鉴权通过
        Session session = SessionManager.getInstance().get(simNumber);
        if (session == null) {
            log.error("device:{} auth failed,session invalidated", simNumber);
            response.setResultCode(ResultCode.FAILURE);
            return response;
        }
        session.setAuthed(deviceInfoPO.getId());
        response.setResultCode(ResultCode.SUCCESS);
        // 设备上线
        deviceInfoService.online(deviceInfoPO.getId());
        return response;
    }
}
